<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="动作标题" prop="actionTitle">
        <el-input
          v-model="queryParams.actionTitle"
          placeholder="请输入动作标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="视频集" prop="episodeId">
        <el-select v-model="queryParams.episodeId" placeholder="请选择视频集" clearable filterable>
          <el-option
            v-for="ep in episodeList"
            :key="ep.episodeId"
            :label="ep.episodeTitle"
            :value="ep.episodeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="actionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="动作ID" align="center" prop="actionId" width="80" />
      <el-table-column label="封面" align="center" width="120">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.coverUrl"
            :src="scope.row.coverUrl"
            :preview-src-list="[scope.row.coverUrl]"
            fit="cover"
            style="width: 100px; height: 56px; border-radius: 4px;"
          />
          <span v-else style="color: #909399;">暂无封面</span>
        </template>
      </el-table-column>
      <el-table-column label="动作标题" align="center" prop="actionTitle" :show-overflow-tooltip="true" min-width="160" />
      <el-table-column label="动作描述" align="center" prop="actionDesc" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="视频集" align="center" min-width="150">
        <template slot-scope="scope">
          <span>{{ getEpisodeTitle(scope.row.episodeId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间(秒)" align="center" prop="startTime" width="120" />
      <el-table-column label="结束时间(秒)" align="center" prop="endTime" width="120" />
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分解动作对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="视频集" prop="episodeId">
          <el-select v-model="form.episodeId" placeholder="请选择视频集" filterable style="width: 100%;" @change="handleEpisodeChange">
            <el-option
              v-for="ep in episodeList"
              :key="ep.episodeId"
              :label="ep.episodeTitle"
              :value="ep.episodeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="动作标题" prop="actionTitle">
          <el-input v-model="form.actionTitle" placeholder="请输入动作标题" />
        </el-form-item>
        <el-form-item label="动作描述">
          <el-input v-model="form.actionDesc" type="textarea" :rows="3" placeholder="请输入动作描述" />
        </el-form-item>
        <el-form-item label="开始时间(秒)" prop="startTime">
          <el-input-number v-model="form.startTime" :min="0" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="结束时间(秒)" prop="endTime">
          <el-input-number v-model="form.endTime" :min="0" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="视频">
          <el-upload
            :action="uploadBase + '/admin/video/upload-action-video'"
            :headers="uploadHeaders"
            :data="{ courseId: form.courseId, episodeId: form.episodeId, actionId: form.actionId }"
            :show-file-list="false"
            :disabled="!form.actionId"
            :on-success="onActionVideoSuccess"
            :before-upload="beforeActionVideoUpload"
          >
            <el-button type="primary" :disabled="!form.actionId">上传视频</el-button>
          </el-upload>
          <div v-if="form.videoUrl" style="margin-top: 10px;">
            <a :href="form.videoUrl" target="_blank" style="color: #409EFF;">预览视频</a>
          </div>
          <div v-if="!form.actionId" class="tip" style="color: #909399; margin-top: 6px;">请先保存分解动作基本信息后再上传视频</div>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
            :action="uploadBase + '/admin/video/upload-action-cover'"
            :headers="uploadHeaders"
            :data="{ courseId: form.courseId, episodeId: form.episodeId, actionId: form.actionId }"
            :show-file-list="false"
            :disabled="!form.actionId"
            :on-success="onActionCoverSuccess"
            :before-upload="beforeActionCoverUpload"
          >
            <el-button :disabled="!form.actionId">上传封面</el-button>
          </el-upload>
          <div v-if="form.coverUrl" style="margin-top: 10px;">
            <img :src="form.coverUrl" class="thumb" />
          </div>
          <div v-if="!form.actionId" class="tip" style="color: #909399; margin-top: 6px;">请先保存分解动作基本信息后再上传封面</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { listAction, createAction, updateAction, delAction } from "@/api/video/action"
import { listEpisode } from "@/api/video/episode"

export default {
  name: "Action",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分解动作表格数据
      actionList: [],
      // 视频集列表（用于下拉选择）
      episodeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 上传基础路径
      uploadBase: process.env.VUE_APP_BASE_API || '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        actionTitle: null,
        episodeId: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        episodeId: [
          { required: true, message: "视频集不能为空", trigger: "change" }
        ],
        actionTitle: [
          { required: true, message: "动作标题不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    uploadHeaders() {
      const token = getToken()
      return token ? { Authorization: 'Bearer ' + token } : {}
    }
  },
  created() {
    this.getList()
    this.loadEpisodeList()
  },
  methods: {
    /** 查询分解动作列表 */
    getList() {
      this.loading = true
      listAction(this.queryParams).then(response => {
        this.actionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 加载视频集列表 */
    loadEpisodeList() {
      listEpisode().then(response => {
        const res = response.data || response
        if (res && (res.code === 200 || res.code === 0 || res.success)) {
          this.episodeList = res.rows || res.data || []
        } else {
          this.episodeList = []
        }
      }).catch(() => {
        this.episodeList = []
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        actionId: null,
        episodeId: null,
        actionTitle: null,
        actionDesc: null,
        startTime: null,
        endTime: null,
        sort: 0,
        status: "0",
        videoUrl: null,
        coverUrl: null,
        courseId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.actionId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加分解动作"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const actionId = row.actionId || this.ids[0]
      // 查找对应的视频集信息以获取courseId
      const episode = this.episodeList.find(ep => ep.episodeId === row.episodeId)
      this.form = {
        actionId: row.actionId,
        episodeId: row.episodeId,
        actionTitle: row.actionTitle,
        actionDesc: row.actionDesc || null,
        startTime: row.startTime,
        endTime: row.endTime,
        sort: row.sort || 0,
        status: row.status || "0",
        videoUrl: row.videoUrl || null,
        coverUrl: row.coverUrl || null,
        courseId: episode ? episode.courseId : null
      }
      this.open = true
      this.title = "修改分解动作"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 验证结束时间必须大于开始时间
          if (this.form.endTime <= this.form.startTime) {
            this.$message.error('结束时间必须大于开始时间')
            return
          }
          // 获取视频集的courseId
          const episode = this.episodeList.find(ep => ep.episodeId === this.form.episodeId)
          if (!episode) {
            this.$message.error('请选择有效的视频集')
            return
          }
          const payload = {
            episodeId: this.form.episodeId,
            actionTitle: this.form.actionTitle,
            actionDesc: this.form.actionDesc,
            startTime: this.form.startTime,
            endTime: this.form.endTime,
            sort: this.form.sort,
            status: this.form.status
          }
          // 如果有视频URL和封面URL，也一起提交
          if (this.form.videoUrl) {
            payload.videoUrl = this.form.videoUrl
          }
          if (this.form.coverUrl) {
            payload.coverUrl = this.form.coverUrl
          }
          // 设置courseId
          this.form.courseId = episode.courseId
          if (this.form.actionId != null) {
            payload.actionId = this.form.actionId
            updateAction(payload).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            createAction(payload).then(response => {
              const res = response.data || response
              console.log('res', res)
              if (res && res.actionId !== undefined) {
                // 获取返回的actionId，用于后续上传
                const actionId = (res.data && res.data.actionId) || res.actionId
                if (actionId) {
                  this.form.actionId = actionId
                  this.$modal.msgSuccess("新增成功，可以继续上传视频和封面")
                  // 不关闭弹框，允许继续上传
                } else {
                  this.$modal.msgSuccess("新增成功")
                  this.open = false
                  this.getList()
                }
              } else {
                this.$message.error(res.msg || '新增失败')
              }
            }).catch(error => {
              console.error('新增分解动作失败:', error)
              this.$message.error('新增失败')
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const actionIds = row ? [row.actionId] : this.ids
      this.$modal.confirm('是否确认删除分解动作编号为"' + actionIds.join(',') + '"的数据项？').then(() => {
        return delAction(actionIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 根据episodeId获取视频集标题
    getEpisodeTitle(episodeId) {
      const episode = this.episodeList.find(ep => ep.episodeId === episodeId)
      return episode ? episode.episodeTitle : '未知'
    },
    // 视频集选择变化时更新courseId
    handleEpisodeChange(episodeId) {
      const episode = this.episodeList.find(ep => ep.episodeId === episodeId)
      if (episode) {
        this.form.courseId = episode.courseId
      }
    },
    // ========== 上传相关方法 ==========
    beforeActionVideoUpload(file) {
      const ok = file.size < 512 * 1024 * 1024
      if (!ok) this.$message.error('动作视频不能超过 512MB!')
      if (!this.form.actionId) this.$message.warning('请先保存分解动作基本信息')
      return ok && !!this.form.actionId
    },
    onActionVideoSuccess(res) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        this.form.videoUrl = url
        this.$message.success('视频上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    beforeActionCoverUpload(file) {
      const ok = file.size < 5 * 1024 * 1024
      if (!ok) this.$message.error('动作封面不能超过 5MB!')
      if (!this.form.actionId) this.$message.warning('请先保存分解动作基本信息')
      return ok && !!this.form.actionId
    },
    onActionCoverSuccess(res) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        this.form.coverUrl = url
        this.$message.success('封面上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    }
  }
}
</script>

<style scoped>
.thumb {
  width: 120px;
  height: 68px;
  object-fit: cover;
  border: 1px solid #eee;
  border-radius: 4px;
}
.tip {
  color: #909399;
  margin-top: 6px;
}
</style>

